<style>
.chooseIcon {
  border: 1px solid;
}
</style>

<template>
  <div class="menu">
    <Layout>
      <Sider :style="{background:'#fff'}">
        <!-- 树结构 -->
        <Tree :data="menuData" @on-select-change="selectTree"></Tree>
      </Sider>
      <Content>
        <MenuListTable
          v-show="!showEdit"
          @setCurrentMenuEvent="setCurrentMenu"
          @addMenuEvent="addMenu"
          :menuNodes="menuNodes"
          :allMenu="allMenu"
          @menuDataChangeEvent="menuDataChangeListen"
          @deleteMenuEvent="deleteMenuListen"
          @stepIntoSubMenEvent="stepIntoSubMenuListen"
          @editMenuIconEvent="editMenuIconListen"
          @backToParentMenuEvent="backToParentMenuListen"
        ></MenuListTable>
        <MenuEdit
          v-if="showEdit"
          :Menu="currentMenu"
          @close="cancelEdit"
          @refreshData="refreshData"
        ></MenuEdit>
      </Content>
    </Layout>
    <Modal v-model="icon_modal" title="编辑图标" width="888" @on-ok="icon_edit_ok">
      <Row style="text-align:center;">请选择颜色:
        <ColorPicker v-model="icon_color"/>
      </Row>
      <Row style="max-height:600px;">
        <Scroll>
          <table style="width: 100%;min-height: 200px;margin-top: 10px;">
            <tbody>
              <tr v-for="(tr,ind1) in icons" style="cursor:pointer;" :key="ind1">
                <td
                  style="text-align: center;"
                  v-for="(td,ind2) in tr"
                  :class="{chooseIcon: select_icon == td}"
                  @click="chooseIcon(td)"
                  :key="ind2"
                >
                  <Icon :type="td" size="22" :color="icon_color"></Icon>
                </td>
              </tr>
            </tbody>
          </table>
        </Scroll>
      </Row>
    </Modal>
  </div>
</template>
<script>
import { mapActions } from 'vuex'

import {
  getMenuById,
  getParentById
// setMenuListToLocalStorage
} from '@/libs/util'
import MenuEdit from './components/menu_edit'
import MenuListTable from './components/menu_list_table'
import ICONS from './icons'

export default {
  name: 'imenu',
  data () {
    return {
      currentMenu: {}, // 当前操作的菜单
      // currentEditMenu: {},
      showEdit: false,
      menuNodes: [], // 当前层级的所有menu
      allMenu: [], // 缓存所有的菜单
      icon_modal: false,
      icon_color: '',
      select_icon: ''
    }
  },
  components: {
    MenuEdit,
    MenuListTable
  },
  computed: {
    menuData () {
      return this.$store.state.menu.treeMenuList
    },
    icons () {
      // 修改图标时的图标
      let size = 20 // 每行显示的图标个数
      let line_data = []

      for (let i = 0; i < ICONS.length; i = i + size) {
        line_data.push(ICONS.slice(i, i + size))
      }
      return line_data
    }
  },
  created () {
    this.getMenus()
  },
  methods: {
    ...mapActions([
      'handleListAllMenu'
    ]),
    selectTree: function (item) {
      // console.log(item)
      // console.log(this.allMenu)
      // 左侧树形菜单列表中选中一个菜单后的操作
      const current = item[0]
      let menu = getMenuById(this.allMenu, current['id'])
      // console.log(menu)

      let parent_name = getParentById(
        this.allMenu,
        current['data']['pId']
      )
      // console.log(parent_name)
      menu['parent_name'] = parent_name['name']
      this.setCurrentMenu(menu)
    },
    setCurrentMenu: function (data) {
      // 编辑菜单
      this.showEdit = true
      this.currentMenu = data
    },
    cancelEdit: function (data) {
      // 取消编辑
      let parent = getMenuById(this.allMenu, this.currentMenu['pId'])
      let nodes = []
      if (parent !== undefined) {
        nodes = parent.nodes
      } else {
        nodes = this.allMenu
      }
      this.menuDataChangeListen(nodes)
      this.currentMenu = {}
      this.showEdit = false
    },
    addMenu: function () {
      // 新增按钮
      console.log(this.currentMenu)
      this.showEdit = true
      let menu = {}
      menu['pId'] = this.currentMenu['id'] || 0
      menu['parent_name'] = this.currentMenu['name'] || '(无) 此项为顶级菜单'
      if (parseInt(menu['pId']) === 0) {
        menu['url'] = '顶级菜单禁止输入'
      }
      this.currentMenu = menu
    },
    menuDataChangeListen (data) {
      this.menuNodes = data
    },

    stepIntoSubMenuListen (data, level) {
      // 菜单列表页进入子菜单
      if (level === 1) {
        // 如果该菜单存在子节点
        this.menuNodes = data
        let parent = getMenuById(this.allMenu, data[0]['pId'])
        this.currentMenu = parent
      } else {
        // 如果该菜单若不存在子节点
        this.parentMenu = data// 将父节点数据路由
        this.currentMenu = data
      }
    },

    backToParentMenuListen (data) {
    // console.log('backToParentMenuListen',data, this.allMenu)
      // 菜单列表页点返回
      let parent = getMenuById(this.allMenu, data[0]['pId'])
      // console.log(parent)

      parent = getMenuById(this.allMenu, parent['pId'])
      let nodes = []
      if (parent !== undefined) {
        nodes = parent.nodes
      } else {
        nodes = this.allMenu
      }
      this.menuDataChangeListen(nodes)
    },
    deleteMenuListen (id) {
      // 删除菜单
      this.$store.dispatch('handleDeleteMenu', {
        MENU_ID: id
      }).then(response => {
        if (response && response.data && response.data.success === true) {
          this.$Message.success('成功!')
          this.refreshData()
        } else {
          this.$Message.error('失败!')
        }
      })
        .catch(res => {
          console.error(err)
        })
    },
    icon_edit_ok () {
      // 编辑图标
      this.$store.dispatch('handleEditMenuIcon', {
        // MENU_ID: this.currentEditMenu["id"],
        MENU_ID: this.currentMenu['id'],
        MENU_ICON: this.select_icon,
        ICON: this.select_icon
      }).then(response => {
        if (response && response.data && response.data.success === true) {
          this.currentMenu['ICON'] = this.select_icon
          this.$Message.success('成功!')
        } else {
          this.$Message.error('失败!')
        }
      })
    },
    chooseIcon (icon) {
      // 选中图标
      this.select_icon = icon
    },
    editMenuIconListen (data) {
      this.icon_modal = true
      // this.currentEditMenu = data;
      this.currentMenu = data
    },
    getMenus () {
      // 获取树的根节点数据
      this.handleListAllMenu().then(res => {
        if (!res.data) {
          res.data = {}
        }
        const treenodes = JSON.parse(res.data.result.zTreeNodes) || []
        // console.log('获取树的根节点数据 handleListAllMenu', treenodes)
        // console.log('获取树的根节点数据 handleListAllMenu', treenodes)

        this.$store.dispatch('updateMenulist', treenodes)

        this.menuNodes = treenodes
        this.allMenu = treenodes

        this.$store.dispatch('updateTreeMenulist', treenodes).then(() => {
          // setMenuListToLocalStorage(treenodes)
          // console.log(res.data.result.zTreeNodes)
        })
      }).catch(err => {
        console.error(err)
      })
    },
    refreshData () {
      this.getMenus()
      this.showEdit = false
    }
  }
}
</script>
<style>
</style>
